package com.leo.javase.thread.itcast;

/**
 * 子线程循环10次，接着主线程循环100，接着又回到子线程循环10次，接着再回到主线程又循环100，如此循环50次
 * @author Lian
 */
public class TraditionalThreadCommunicate {

	public static void main(String[] args) {
		final Bussniss bs = new Bussniss();
		
		//子线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<50; i++){
					bs.sub(i);
				}
			}
		}).start();
		
		//主线程
		for(int i=0; i<50; i++){
			bs.main(i);
		}
	}
}
class Bussniss{
	private boolean flag = true;
	
	public synchronized void sub(int i){
		while(!flag){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int j=0; j<10; j++){
			System.out.println("Sub thread i="+(i+1)+",j="+(j+1));
		}
		flag = false;
		notify();
	}
	
	public synchronized void main(int i){
		while(flag){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		for(int j=0; j<100; j++){
			System.out.println("Main thread i="+(i+1)+",j="+(j+1));
		}
		
		flag = true;
		notify();
	}
}
